//package com.ptc.core.components.export.table;

package ext.generic.util;

import com.ptc.core.components.forms.*;
import com.ptc.core.components.util.FeedbackMessage;
import com.ptc.core.ui.resources.FeedbackType;
import com.ptc.netmarkets.util.beans.NmCommandBean;

import java.io.File;

import java.lang.reflect.InvocationTargetException;

import java.net.URL;

import java.rmi.RemoteException;

import java.util.regex.Pattern;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import wt.ixb.clientAccess.StandardIXBService;

import wt.method.RemoteAccess;

import wt.method.RemoteMethodServer;

import wt.util.WTException;

/**
 *通用的表格数据导出到excel方法类
 */
public class ExportListCommands implements RemoteAccess
{
    public static String CLASSNAME = ExportListCommands.class.getName();
    public static final String FILE_CONTENT = "fileContent";
    public static final String FILE_HEADERS = "fileHeaders";
    public static final String ROW_DELIM = "row_delim";
    public static final String FILE_TYPE = "exportTableFileType";
    public static final String FILE_NAME = "exportTableFile";
    public static final String DELIM = "delim";
    public static final String EXPORT_FILE = "exportFile";
    public static final String EXPORT_SESSION_KEY = "exportSessionKey";
    private static boolean VERBOSE = true;

    public ExportListCommands()
    {
    }
    /**
     *导出方法入口,响应客户端的请求
     * @param nmcommandbean
     * @return
     * @throws Exception
     */
    public static FormResult exportXLS(NmCommandBean nmcommandbean) throws Exception
    {
        FormResult result = null;
        if (!RemoteMethodServer.ServerFlag)
        {
            try
            {
                Class aclass[] =
                { NmCommandBean.class };
                Object aobj[] =
                { nmcommandbean };
                result = (FormResult) RemoteMethodServer.getDefault().invoke("exportXLS", CLASSNAME, null, aclass, aobj);
                return result;
            }
            catch (InvocationTargetException invocationtargetexception)
            {
                Throwable throwable = invocationtargetexception.getTargetException();
                if (throwable instanceof WTException)
                {
                    throw (WTException) throwable;
                }
                else
                {
                    Object aobj2[] =
                    { "exportXLS" };
                    throw new WTException(throwable, "wt.fc.fcResource", "0", aobj2);
                }
            }
            catch (RemoteException remoteexception)
            {
                Object aobj1[] =
                { "exportXLS" };
                throw new WTException(remoteexception, "wt.fc.fcResource", "0", aobj1);
            }
        }
        ExportListCommands exportlistcommands = new ExportListCommands();
        return exportlistcommands.doExportXLS(nmcommandbean);
    }

    /**
     *具体的导出excel方法
     * @param nmcommandbean
     * @return
     * @throws Exception
     */
    public FormResult doExportXLS(NmCommandBean nmcommandbean) throws Exception
    {
        if (VERBOSE)
            System.out.println(">>>" + CLASSNAME + ".doExportXLS()");
        FormResult formresult = new FormResult();
        formresult.setStatus(FormProcessingStatus.SUCCESS);
        String s = nmcommandbean.getTextParameter("exportTableFileType");
        //ExportListWriter exportlistwriter = ExportListWriterFactory.getExportWriter(s);
        ExportToExcel exportlistwriter = new ExportToExcel();
        exportlistwriter.setFileName((new StringBuilder()).append(nmcommandbean.getTextParameter("exportTableFile")).append(".xlsx").toString());
        //exportlistwriter.setFileName((new StringBuilder()).append(nmcommandbean.getTextParameter("exportTableFile")).append("dafdd").toString());
        boolean flag = parseAndWriteTempXLSFileContent(exportlistwriter, nmcommandbean, formresult);
        if (flag)
        {
            exportlistwriter.close();
            String s1 = getRedirectToTempFile(exportlistwriter, nmcommandbean);
            formresult.setNextAction(FormResultAction.LOAD_OPENER_URL);
            formresult.setURL(s1);
        }
        else
        {
            formresult.setStatus(FormProcessingStatus.FAILURE);
            formresult.setNextAction(FormResultAction.JAVASCRIPT);
            formresult.setJavascript("top.finishServerSideExport();");
        }
        if (VERBOSE)
            System.out.println("<<<" + CLASSNAME + ".doExportXLS()");
        return formresult;
    }

    /**
     *解析表格内容，然后写入到Excel中
     * @param exportlistwriter
     * @param nmcommandbean
     * @param formresult
     * @return
     * @throws Exception
     */
    protected boolean parseAndWriteTempXLSFileContent(ExportToExcel exportlistwriter, NmCommandBean nmcommandbean, FormResult formresult) throws Exception
    {
        if (VERBOSE)
            System.out.println(">>>" + CLASSNAME + ".parseAndWriteTempXLSFileContent()");
        String s = nmcommandbean.getTextParameter("fileContent");
        String s1 = nmcommandbean.getTextParameter("fileHeaders");
        String s2 = nmcommandbean.getTextParameter("delim");
        String s3 = nmcommandbean.getTextParameter("exportSessionKey");
        String s4 = nmcommandbean.getTextParameter("row_delim");
        File file = getTemporaryFile(nmcommandbean);
        exportlistwriter.open(file, nmcommandbean);
        if (s != null)
        {
            exportlistwriter.writeColumnHeaders(s1, s2);
            if (VERBOSE)
                System.out.println("	完成表头行写入.");
            String as[] = s.split(Pattern.quote(s4));
            int i = ExportToExcel.getExportFullListLimit();
            boolean flag = as.length >= i;
            if (!flag)
            {
                i = as.length;
            }

            if (VERBOSE)
            {
                System.out.println("	共有" + i + "行数据");
                System.out.println("    开始数据行写入.");
            }
            for (int j = 0; j < i; j++)
            {
                String s6 = as[j];
                java.util.List list = ExportToExcel.parseStringToList(s6, s2);
                exportlistwriter.writeRowData(list, (j + 1));
            }
            if (VERBOSE)
                System.out.println("    完成数据行写入.");
            if (flag)
            {
                String s5 = ExportToExcel.getOverLimitMessage();
                FeedbackMessage feedbackmessage = new FeedbackMessage(FeedbackType.SUCCESS, null, "", null, new String[]
                        { s5 });
                formresult.addFeedbackMessage(feedbackmessage);
            }
            if (VERBOSE)
                System.out.println("<<<" + CLASSNAME + ".parseAndWriteTempXLSFileContent()---result=true");
            return true;
        }
        else
        {
            nmcommandbean.getRequest().getSession().setAttribute((new StringBuilder()).append("exportFile").append(s3).toString(), exportlistwriter);
            if (VERBOSE)
                System.out.println("<<<" + CLASSNAME + ".parseAndWriteTempXLSFileContent()---result=false");
            return false;
        }
    }

    protected File getTemporaryFile(NmCommandBean nmcommandbean)
    {
        //File file = (File)nmcommandbean.getRequest().getSession().getServletContext().getAttribute("javax.servlet.context.tempdir");
        //创建excel临时文件
        File file = StandardIXBService.getSaveDirectoryOnServer();
        if (VERBOSE)
            System.out.println("	temp file=" + file.getAbsolutePath());
        return file;
    }

    public String getRedirectToTempFile(ExportToExcel exportlistwriter, NmCommandBean nmcommandbean) throws WTException
    {
        try
        {
            URL url = exportlistwriter.getDownloadUrl(nmcommandbean);
            return url.toExternalForm();
        }
        catch (Exception exception)
        {
            throw new WTException(exception);
        }
    }
}
